package com.haipumi.listeners;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.web.context.support.WebApplicationObjectSupport;

import com.haipumi.beans.haipumi_skin;
import com.haipumi.biz.IBackSkinBiz;
import com.haipumi.utils.CommonData;

public class SkinListener extends WebApplicationObjectSupport implements ApplicationListener<ContextRefreshedEvent> {
	
	@Autowired
    private IBackSkinBiz backSkinBiz;
	
	private ServletContext servletContext;
	
    @Override
	protected void initServletContext(ServletContext servletContext) {
		this.servletContext=servletContext;
	}
    @Override
    public void onApplicationEvent(ContextRefreshedEvent ev) {
        //防止重复执行。
        if(ev.getApplicationContext().getParent() == null){
        	//访问数据库,得到所有的商品存到application中
    		List<haipumi_skin> list=backSkinBiz.findAllDisplaySkin();
    		List<haipumi_skin> jdList=new ArrayList<haipumi_skin>();//经典背景图片
    		List<haipumi_skin> jjList=new ArrayList<haipumi_skin>();//季节背景图片
    		List<haipumi_skin> rwList=new ArrayList<haipumi_skin>();//人物背景图片
    		List<haipumi_skin> xqxList=new ArrayList<haipumi_skin>();//小清新背景图片
    		Map skinMap=new HashMap<String,List<haipumi_skin>>();//所有类别的背景图片集合
    		for(int i=0;i<list.size();i++){//将所有的背景图片分类
    			String imageName=list.get(i).getSimage();
    			String type=imageName.substring(0, imageName.indexOf("_"));
    			if("jd".equals(type)){
    				jdList.add(list.get(i));
    			}else if("jj".equals(type)){
    				jjList.add(list.get(i));
    			}else if("rw".equals(type)){
    				rwList.add(list.get(i));
    			}else if("xqx".equals(type)){
    				xqxList.add(list.get(i));
    			}
    		}
    		skinMap.put("jdList", jdList);
    		skinMap.put("jjList", jjList);
    		skinMap.put("rwList", rwList);
    		skinMap.put("xqxList", xqxList);
    		
    		servletContext.setAttribute(CommonData.APPLICATIONSKINLIST, skinMap);
        }
        
    }
 
}
